<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="图标" prop="icon">
        <!--        <el-input v-model="formData.icon" placeholder="请输入图标" />-->
        <EFIconSelect v-model="formData.icon" :editable="false" />
      </el-form-item>
      <el-form-item label="资源类型" prop="category">
        <!--        <el-input v-model="formData.category" placeholder="请输入资源类型" />-->
        <el-select
          v-model="formData.category"
          placeholder="请选择资源类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in ResourceTypesDicData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="父级资源" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="centerTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择父级资源"
        />
      </el-form-item>
      <el-form-item label="资源代码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入资源代码" :disabled="!formTypeCreate">
          <template #append v-if="formTypeCreate">
            <el-button
              :icon="Pointer"
              :disabled="!formTypeCreate"
              title="点击随机生成"
              style="cursor: pointer"
              @click.stop="formData.code = generateRandomString(10)"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="资源名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入资源名称" />
      </el-form-item>
      <!--      <el-form-item label="资源别名" prop="alias">-->
      <!--        <el-input v-model="formData.alias" placeholder="请输入资源别名" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="请求地址" prop="path">-->
      <!--        <el-input v-model="formData.path" placeholder="请输入请求地址" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="资源资源" prop="source">-->
      <!--        <el-input v-model="formData.source" placeholder="请输入资源资源" />-->
      <!--      </el-form-item>-->
      <el-form-item label="排序" prop="sort">
        <el-input type="number" v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <!--      <el-form-item label="是否打开新页面" prop="isOpen">-->
      <!--        <el-input v-model="formData.isOpen" placeholder="请输入是否打开新页面" />-->
      <!--      </el-form-item>-->
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" :rows="5" v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CenterApi, CenterVO } from '@/api/res/ResCenter'
import { defaultProps, handleTree } from '@/utils/tree'
import { ResourceTypesDicData } from '@/api/res/ResCenter/ResourceCtrl'
import EFIconSelect from '@/components/Icon/src/EFIconSelect.vue'
import { generateRandomString } from '@/utils'
import { Pointer } from '@element-plus/icons-vue'

/** 资源中心 表单 */
defineOptions({ name: 'CenterForm' })




const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  parentId: undefined,
  code: undefined,
  name: undefined,
  alias: undefined,
  path: undefined,
  source: undefined,
  sort: undefined,
  category: undefined,
  action: undefined,
  isOpen: undefined,
  remark: undefined,
  createDept: undefined,
  status: undefined,
  icon: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref
const centerTree = ref() // 树形结构

const formTypeCreate = computed(() => formType.value === 'create') // 是否为新增
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if (formTypeCreate) {
    formData.value.code = generateRandomString(10)
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CenterApi.getCenter(id)
    } finally {
      formLoading.value = false
    }
  }
  await getCenterTree()
}

const addSubItem = async (formItem: CenterVO,callback?: (result: any) => void) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.create')
  formType.value = 'create'
  resetForm()
  formData.value.category = formItem.category
  formData.value.code = generateRandomString(10)
  formData.value.parentId = formItem.id

  await getCenterTree()

  if (callback) {
    callback()
  }
  // debugger
  // if (formTypeCreate) {
  //
}
defineExpose({ open, addSubItem }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CenterVO
    if (formType.value === 'create') {
      await CenterApi.createCenter(data)
      message.success(t('common.createSuccess'))
    } else {
      await CenterApi.updateCenter(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    parentId: undefined,
    code: undefined,
    name: undefined,
    alias: undefined,
    path: undefined,
    source: undefined,
    sort: undefined,
    category: undefined,
    action: undefined,
    isOpen: undefined,
    remark: undefined,
    createDept: undefined,
    status: undefined,
    icon: undefined
  }
  formRef.value?.resetFields()
}

/** 获得资源中心树 */
const getCenterTree = async () => {
  centerTree.value = []
  const data = await CenterApi.getCenterList()
  const root: Tree = { id: 0, name: '顶级资源中心', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  centerTree.value.push(root)
}
</script>
